/**
 * 获取uuid
 */
export function getUUID() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
		return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
	})
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
	return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId') {
	var res = []
	var temp = {}
	for (var i = 0; i < data.length; i++) {
		temp[data[i][id]] = data[i]
	}
	for (var k = 0; k < data.length; k++) {
		if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
			if (!temp[data[k][pid]]['children']) {
				temp[data[k][pid]]['children'] = []
			}
			if (!temp[data[k][pid]]['_level']) {
				temp[data[k][pid]]['_level'] = 1
			}
			data[k]['_level'] = temp[data[k][pid]]._level + 1
			temp[data[k][pid]]['children'].push(data[k])
		} else {
			res.push(data[k])
		}
	}
	return res
}

/**
 * 用子id得到树形数据id及父级id
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function getTreeId(data, id = 0, idLable = 'id', pid = 'parentId', res = []) {
	for (var i = 0; i < data.length; i++) {
		if (data[i][idLable] === id) {
			res.unshift(data[i][idLable])
			if (data[i][pid] !== -1) {
				getTreeId(data, data[i][pid], idLable, pid, res)
			}
			break
		}
	}
	return res
}

/**
 * 获取视频的首帧图片
 * @param {*} url
 * @param {*} width
 * @param {*} height
 */
export function getFrameImg({
	url,
	width = 200,
	height = 150
}) {
	return new Promise(function(resolve, reject) {
		if (!url) {
			resolve('')
		}
		var reg = /(.*)\.(jpg|jpeg|png)$/;
		if (reg.test(url)) {
			resolve(url)
		}
		var video = document.createElement("VIDEO");
		video.src = url;
		video.setAttribute('crossOrigin', 'anonymous');
		video.addEventListener('loadeddata', function() {
			var canvas = document.createElement("canvas");
			canvas.getContext('2d').drawImage(video, 0, 0, width, height);
			resolve(canvas.toDataURL("image/png"))
		});
	})
}
